package util

import (
	"fmt"
	"io"
	"os"
)

func ReadLastRows(filepath string, num int) (string, error) {
	fileHandle, err := os.Open(filepath)
	if err != nil {
		return "", err
	}
	defer fileHandle.Close()

	line := ""
	var cursor int64 = 0
	stat, _ := fileHandle.Stat()
	filesize := stat.Size()
	cou := 0
	var off int64 = 0
	for {
		cursor -= 1
		off, _ = fileHandle.Seek(cursor, io.SeekEnd)

		char := make([]byte, 1)
		fileHandle.Read(char)

		if cursor != -1 && (char[0] == 10 || char[0] == 13) { // stop if we find a line
			cou++
			if cou >= num {
				// fmt.Println("line: ", cou, cursor, off)
				line = getString(fileHandle, off)
				break
			}
		}

		if cursor == -filesize { // stop if we are at the begining
			line = getString(fileHandle, off)
			break
		}
	}

	return line, nil
}

func getString(fileHandle *os.File, off int64) string {
	buf := make([]byte, 102400)
	n, err := fileHandle.ReadAt(buf, off)
	if err != io.EOF {
		fmt.Println(err)
	}
	buf = buf[:n]
	return fmt.Sprintf("%s", buf)
}
